import os
import uuid
import oss2


class OSSUtil:
    def __init__(self, endpoint=None,
                 access_key_id=None, access_key_secret=None, bucket_name=None, region=None):
        self.endpoint = endpoint
        self.bucket_name = bucket_name
        self.region = region
        self.access_key_id = access_key_id
        self.access_key_secret = access_key_secret

        self.auth = oss2.AuthV4(self.access_key_id, self.access_key_secret)

        self.bucket = oss2.Bucket(self.auth, self.endpoint, self.bucket_name, region=self.region)

    def upload_file(self, local_file, custom_name=None):
        """
        上传文件到OSS

        :param local_file: 本地文件路径
        :param custom_name: 自定义远程文件名（可选）
        :return: OSS上的文件Key
        """
        object_name = custom_name if custom_name else self.gen_object_name(local_file)
        self.bucket.put_object_from_file(object_name, local_file)
        return object_name

    def get_public_url(self, object_name):
        """
        获取文件的公共访问地址（仅限公共读Bucket）

        :param object_name: 文件Key
        :return: 公共URL
        """
        return f"{self.endpoint}/{self.bucket_name}/{object_name}"

    def get_signed_url(self, object_name, expires=3600):
        """
        获取带签名的临时访问URL

        :param object_name: 文件Key
        :param expires: 过期时间（秒）
        :return: 带签名的URL
        """
        return self.bucket.sign_url('GET', object_name, expires)

    @staticmethod
    def gen_object_name(file_name):
        """
        生成文件名
        :param file_name: 文件名
        :return: 文件名
        """
        ext = os.path.splitext(file_name)[1]
        return f"{uuid.uuid4().hex}{ext}"